let item_tpl = require('./cmt/cmt-item.html');
let base_tpl = require('./cmt/base.html');
let reply_tpl = require('./cmt/reply-item.html');
let storage = require('./lib/storage').default;
let md5 = require("md5");
const recorder = require("./cmt/recorder").default;
require('./lib/lazyload');
window.doT = require('./lib/doT');


const JS_URL = document.currentScript.src;

global.QCmt = window.QCmt = {

    STATIC: {
        emotion: './Emotion.js',
        Recorder: './libs/recorder.mp3.min.js',
        waveview: './libs/waveview.js',
        imageCompression: './libs/browser-image-compression.min.js'
    },

    option: {
        target: '#comment',
        data_id: 1,
        type: 'qz',
        api_server: '',
        load_url: '/?qcmt=load',
        upload_url: '/?qcmt=upload',
        submit_url: '/?qcmt=sumbit',
        action_url: '/?qcmt=action',
        callback: '',
        default_avatar: '',
        cdn_url: '',
        user_link: null,
        dialog: false,
        base_url:'',
        allow_anonymous: false,
        anonymous_avatars: [
            'static/images/avatar/1.jpg',
            'static/images/avatar/2.jpg',
            'static/images/avatar/3.jpg',
            'static/images/avatar/4.jpg',
            'static/images/avatar/5.jpg',
        ],
        getUserId: null,
        submit_interval: 10, // 评论间隔时间(秒)
        content_min_length: 2, // 评论最小长度
        content_max_length: 500, // 评论最大长度
        current_user_id: '', // 添加current_user_id配置
        headers: {}, // 添加自定义headers配置
    },

    imageExtensions: ['jpg', 'jpeg', 'gif', 'png'],
    audioExtensions: ['mp3', 'wav'],

    comment: {
        content: '',
        files: [],
        at: '',
        data_id: ''
    },
    setBaseUrl(url){
        this.option.base_url=url;
        localStorage.setItem('QUrl',url);
    },
    setOption(option){
        this.option=Object.assign(this.option,option);
        this.page=1;
        this.init(this.option);
        this.option.dialog = false;
    },
    dialog(option) {
        console.log('#qcmt-container', $('#qcmt-container').length)
        this.option.dialog = true;

        if (!$('#qcmt-container').length) {
            this.init(option);
        } else {
            $('#qcmt-dialog-box').addClass('qcmt-dialog').css("bottom", 0).find('.qcmt-mask').show();
        }
    },
    init(option) {
        this.page = 1;
        option && Object.assign(this.option, option);
        this.comment.data_id = this.option.data_id;

        // 检查目标元素是否存在
        if(!$(this['option'].target).length) {
            console.warn('QCmt: 找不到目标元素 ' + this.option.target);
            return false;
        }

        // 如果没有设置current_user_id,使用getUserId
        if(!this.option.current_user_id && this.option.getUserId) {
            this.option.current_user_id = this.option.getUserId();
        }

        if(!this.option.getUserId) {
            this.option.getUserId = () => {
                let anonymousId = localStorage.getItem('qcmt_anonymous_id');
                if(!anonymousId) {
                    anonymousId = this.generateUserId();
                    localStorage.setItem('qcmt_anonymous_id', anonymousId);
                }
                return anonymousId;
            };
        }

        console.log('this.comment.data_id',this.comment.data_id);
        console.log('this.option.current_user_id',this.option.current_user_id);

        var QUrl=localStorage.getItem('QUrl');

        if(!this.option.base_url && QUrl){
            this.option.base_url=QUrl;
        }

        if (!$('.QCmt-css').length) {
            $('head').append('<link rel="stylesheet" class="QCmt-css" href="' + this.url() + '/static/css/comment.css">');
        }

        let _this = this;
        this.require(['emotion'], () => {
            // 渲染基础模板
            $(_this['option'].target).html(doT.template(base_tpl)(_this.option));

            const userId = _this.option.getUserId();
            
            if(_this.option.allow_anonymous && userId.toString().startsWith('anonymous_')) {
                const savedNickname = localStorage.getItem('qcmt_anonymous_nickname');
                const savedAvatar = localStorage.getItem('qcmt_anonymous_avatar');
                
                if(!savedNickname || !savedAvatar) {
                    const commentBox = $('#qcmt-container .qcmt-input-box');
                    if(commentBox.length) {
                        commentBox.before(`
                            <div class="qcmt-anonymous-form">
                                <div class="qcmt-input-group">
                                    <input type="text" 
                                           class="qcmt-anonymous-nickname" 
                                           placeholder="请输入昵称(必填)" 
                                           maxlength="20">
                                    <input type="email" class="qcmt-anonymous-email" placeholder="邮箱(选填,有回复时通知)" maxlength="100">
                                </div>
                                <div class="qcmt-avatar-list">
                                    ${_this.option.anonymous_avatars.map(avatar => 
                                        `<img src="${_this.cdn(avatar)}" 
                                             class="qcmt-avatar-option" 
                                             alt="选择头像">`
                                    ).join('')}
                                </div>
                            </div>
                        `);
                    }
                }
            }

            _this.load();

            $(document).on('click', '#qcmt-mask', () => {
                $('.qcmt-dialog').css("bottom", -2200).find('.qcmt-mask').hide();
            })
            //事件绑定
            $('#qcmt-container').on('click', '.qcmt-face', function (event) {
                _this.require('emotion', () => {
                    if (!$('#sina-emotion').is(':visible')) {
                        $(event.target).sinaEmotion('#qcmt-content');
                    }
                })
            }).on('click', '.qcmt-image', () => {
                $('#qcmt-image').trigger('click');
            }).on('input propertychange', '#qcmt-content', (e) => {
                _this.comment.content = $('#qcmt-content').val();
            }).on('change', '#qcmt-image', (e) => {
                _this.require('imageCompression', () => {
                    _this.ImageUpload(e);
                })
            }).on('click', 'span[data-cmt-sort]', (e) => {
                //评论排序
                var params = $(e.target).data();
                _this.sort = params.cmtSort;
                _this.reload();
            }).on('click', '.qcmt-cancel', (e) => {
                //取消固定
                _this.comment.at = '';
                $('.qcmt-at').html('');
                $('#qcmt-container').removeClass('qcmt-fixed');
                $('.qcmt-dialog').css("bottom", -2200).find('.qcmt-mask').hide();
            }).on('click', '.qcmt-at', (e) => {
                //取消@at
                _this.comment.at = '';
                $('.qcmt-at').html('');
            }).on('click', 'span[data-cmt-action]', (e) => {
                //操作事件
                var data = $(e.currentTarget).data();
                console.log('当前事件', data)
                if (data.cmtAction == 'reply') {
                    //@at 某人
                    _this.comment.at = data;
                    $('#qcmt-container').addClass('qcmt-fixed');
                    $('#qcmt-content').focus();
                    $('.qcmt-at').html('<b>@' + data.nickname + '</b><sup>x</sup>');
                } else {

                    _this.ajax(_this.option.action_url, data, (res) => {
                        if (res.code) {
                            $('b', e.currentTarget).text(res.data);
                        }
                    })
                }
            }).on('click', '.qcmt-btn', (e) => {
                if(!this.submitCheck()) {
                    return;
                }
                
                const userId = _this.option.getUserId();
                
                if(_this.option.allow_anonymous && userId.toString().startsWith('anonymous_')) {
                    let nickname = localStorage.getItem('qcmt_anonymous_nickname');
                    let email = localStorage.getItem('qcmt_anonymous_email');
                    let avatar = localStorage.getItem('qcmt_anonymous_avatar');
                    
                    if(!nickname || !avatar) {
                        nickname = $('.qcmt-anonymous-nickname').val();
                        email = $('.qcmt-anonymous-email').val();
                        avatar = $('.qcmt-avatar-option.selected').attr('src');
                        
                        if(!nickname || !avatar) {
                            return _this.msg('请填写昵称并选择头像', 'error');
                        }
                        
                        // 验证邮箱格式(如果填写了的话)
                        if(email && !this.validateEmail(email)) {
                            return _this.msg('请输入正确的邮箱格式', 'error');
                        }
                        
                        localStorage.setItem('qcmt_anonymous_nickname', nickname);
                        localStorage.setItem('qcmt_anonymous_email', email);
                        localStorage.setItem('qcmt_anonymous_avatar', avatar);
                    }
                    
                    _this.comment.anonymous = {
                        nickname: nickname,
                        avatar: avatar,
                        email: email,
                        anonymous_id: userId
                    };
                }

                console.log('当前评论', _this.comment)

                _this.comment.data_id = _this.option.data_id;
                _this.comment.type = _this.option.type;

                if (!_this.comment.files.length) {
                    //兼容修复
                    _this.comment.files = '';
                }

                _this.ajax(_this.option.submit_url, _this.comment, (res) => {
                    if (res.code) {
                        _this.comment.content = '';
                        _this.comment.files = [];

                        storage.remove('comment_files');
                        $('#qcmt-content').val('');

                        _this.renderFiles();

                        //处理评论新增到页面
                        if (res.data.cmt.length > 0) {
                            var html = doT.template(res.data.type == 'comment' ? item_tpl : reply_tpl)(res.data.cmt);

                            if (res.data.type == 'comment') {
                                $('.qcmt-list').prepend(html);
                                $('.qcmt-list-container').scrollTop(0);
                            } else {
                                //这里是at
                                var at = _this.comment.at;
                                console.log('at', at);
                                // $('data-cmt-id')
                                if (at.cmtId == at.id) {
                                    console.log('at.cmtId == at.id', at.cmtId, at.id, $('.qcmt-sub-list', '[data-cmt-id=' + at.cmtId + ']').length)
                                    if ($('.qcmt-sub-list', '[data-cmt-id=' + at.cmtId + ']').length < 1) {
                                        //没有列表box
                                        $('[data-cmt-id=' + at.cmtId + ']').find('.qcmt-sub').append('<div class="qcmt-sub-list" id="qcmt-' + at.cmtId + '"></div>');
                                    }
                                    $('.qcmt-sub-list', '[data-cmt-id=' + at.cmtId + ']').prepend(html);

                                    var num = parseInt($('.qcmt-cmt-num-' + at.cmtId).text()) + 1;
                                    $('.qcmt-cmt-num-' + at.cmtId).text(num);

                                } else {
                                    console.log('#qcmt-reply-' + at.id, at.cmtId, at.id)
                                    $('#qcmt-reply-' + at.id).after(html);
                                    //原始数目
                                    var num = parseInt($('.qcmt-reply-num-' + at.id).text()) + 1;
                                    $('.qcmt-reply-num-' + at.id).text(num);

                                    console.log('.qcmt-reply-num-' + at.id)

                                }
                            }
                            //新评论的图片支持懒加载
                            window.lazy.updateImages();
                        }

                        _this.comment.at = '';
                        $('.qcmt-at').html('');
                        _this.option.callback && _this.option.callback(_this.comment);

                        // 记录最后提交时间
                        localStorage.setItem('qcmt_last_submit_time', new Date().getTime());
                    }
                })
            }).on('click', '.qcmt-load-more', () => {
                //加载更多
                $('.qcmt-load-more').remove();
                _this.load();
            }).on('click', '.qcmt-load-reply', (e) => {
                //加载更多子评论
                let data = $(e.currentTarget).data();

                _this.ajax(_this.option.load_url, {
                    type: 'reply',
                    data_id: _this.option.data_id,
                    cmt_id: data.id,
                    num: data.num
                }, (res) => {

                    console.log(data.all, data, e.currentTarget)
                    if (res.data.length > 0) {
                        let html = doT.template(reply_tpl)(res.data), num = data.num + res.data.length;
                        $('#qcmt-replys-' + data.id).append(html);
                        window.lazy.updateImages();
                        if (data.all == num) {
                            $(e.currentTarget).remove();
                        } else {
                            $(e.currentTarget).data('num', num).attr('num', num);
                        }
                    }
                })
            }).on('click', '#qcmt-record', () => {
                _this.startRecorder();
            })
            $(document).on('click', '.recwave-mask', () => {
                _this.stopRecorder();
            })

            $('#qcmt-files').on('click', 'li sup', (e) => {
                //更新缓存文件
                var data = $(e.target).data();
                if (typeof data.index != "undefined") {
                    _this.comment.files.splice(data.index, 1);
                    storage.set('comment_files', _this.comment.files);
                    _this.renderFiles();
                }
            })


            this.comment.files = storage.get('comment_files') || [];
            this.renderFiles();

            function updateListContainerHeight() {
                const windowHeight = window.innerHeight;
                const dialogHeight = windowHeight * 0.88; // 对应 max-height: 88%
                const boxHeight = $('.qcmt-box').outerHeight();
                const sortHeight = $('.qcmt-sort').outerHeight();
                const listContainerHeight = dialogHeight - boxHeight - sortHeight - 200;
                
                $('.qcmt-list-container').css({
                    "height": listContainerHeight
                });
            }

            // 在初始化和窗口大小改变时调用
            $(window).on('resize', updateListContainerHeight);
            updateListContainerHeight();

            // 添加图片预览容器
            if(!$('.qcmt-preview').length) {
                $('body').append(`
                    <div class="qcmt-preview">
                        <img class="qcmt-preview-img" src="" alt="预览图片">
                        <div class="qcmt-preview-close"></div>
                    </div>
                `);
            }

            // 绑定图片点击事件
            $('#qcmt-container').on('click', '.qcmt-file-img', function(e) {
                const $preview = $('.qcmt-preview');
                const $previewImg = $('.qcmt-preview-img');
                
                $previewImg.attr('src', $(this).attr('src'));
                
                // 等图片加载完成后显示
                $previewImg.on('load', function() {
                    $preview.addClass('show');
                    setTimeout(() => {
                        $previewImg.addClass('show');
                    }, 50);
                });
            });

            // 绑定关闭预览事件
            $('.qcmt-preview').on('click', function(e) {
                if($(e.target).hasClass('qcmt-preview') || $(e.target).hasClass('qcmt-preview-close')) {
                    const $preview = $('.qcmt-preview');
                    const $previewImg = $('.qcmt-preview-img');
                    
                    $previewImg.removeClass('show');
                    setTimeout(() => {
                        $preview.removeClass('show');
                        $previewImg.attr('src', '');
                    }, 300);
                }
            });
        });

        // 添加头像选择事件
        $(document).on('click', '.qcmt-avatar-option', function() {
            $('.qcmt-avatar-option').removeClass('selected');
            $(this).addClass('selected');
        });
    },
    is_recording: false,
    startRecorder() {
        var _this = this;

        if (this.is_recording) {
            return this.stopRecorder();
        }

        recorder.recOpen(function () {
            $('#qcmt-recwave,.recwave-mask').addClass('on');
            _this.is_recording = true;
        })
    },
    stopRecorder() {
        var _this = this;
        _this.is_recording = false;
        recorder.recStop(function (blob) {
            $('#qcmt-recwave,.recwave-mask').removeClass('on');

            if (blob && blob instanceof Blob) {

                let reader = new FileReader();
                reader.readAsDataURL(blob)
                reader.onload = function (res) {


                    _this.ajax(_this.option.upload_url, {
                        blob: res.target.result,
                        name: new Date().toLocaleString() + '.mp3',
                        type: 'audio'
                    }, (res) => {
                        if (res.data.path) {
                            _this.comment.files.push(res.data.path);
                            storage.set('comment_files', _this.comment.files);
                            _this.renderFiles();
                        }
                    })
                }
            }

        })
    },
    user_link(uid) {
        if (this.isCallback(this.option.user_link)) {
            return this.option.user_link(uid);
        } else {
            return '/user/' + uid;
        }
    },
    parseFiles(files) {
        // console.log(files)
        var html = '';
        if (files) {

            html += '<div class="qcmt-content-files">'
            try {
                files = JSON.parse(files);
            } catch (e) {
            }

            for (var i in files) {
                var extension = files[i].split('.').pop().toLowerCase()

                if (this.imageExtensions.includes(extension)) {
                    html += '<img src="" data-src="' + files[i] + '" class="qcmt-file-img lazyload"/>'
                }

                if (this.audioExtensions.includes(extension)) {
                    html += '<audio preload="none" src="' + QCmt.cdn(files[i]) + '" controls  >  浏览器不支持音频播放</audio>'
                }

            }

            html += '</div>';
        }
        return html;
    },

    url() {
        let Url_Info = this.parseURL(JS_URL),
            _dirs_ = Url_Info['segments'].slice(0, -3);
        return localStorage.getItem('QUrl')|| this.option.base_url ||Url_Info.protocol + '://' + Url_Info.host + '/' + (_dirs_.join('/'));
    },


    cdn(file) {
        // console.log('file',file)
        file = file ? file : this.option.default_avatar;
        return file.indexOf('http') > -1 ? file : ((this.option.cdn_url || this.url()) + '///' + file).replace(/\/{3,}/, '/');
    },
    //重新渲染文件
    renderFiles() {
        var html = '';

        $('#qcmt-files').html('');

        if (!this.comment.files) {
            this.comment.files = [];
            return false;
        }

        for (var i in this.comment.files) {
            var extension = this.comment.files[i].split('.').pop().toLowerCase();

            if (this.imageExtensions.includes(extension)) {
                html += '<li class="qcmt-file"><img src="' + this.comment.files[i] + '"><sup data-index="' + i + '" data-file="' + this.comment.files[i] + '">x</sup></li>';
            } else {
                html += '<li class="qcmt-file"><span class="qcmt-media"><i class="iconfont icon-wav"></i></span><sup data-index="' + i + '" data-file="' + this.comment.files[i] + '">x</sup></li>';
            }


        }
        if (html) {
            $('.qcmt-input-box').addClass('has-file');
            $('#qcmt-files').html(html).show();
        }
    },
    async ImageUpload(event) {
        const imageFile = event.target.files[0], _this = this;
        const options = {
            maxSizeMB: 0.02,
            maxWidthOrHeight: 1080,
            useWebWorker: true,
        }
        console.log(imageFile)
        try {
            const compressedFile = await imageCompression(imageFile, options);

            console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`, ` size ${compressedFile.size / 1024 / 1024} MB`);

            if (compressedFile instanceof Blob) {

                let reader = new FileReader(), _this = this;
                reader.readAsDataURL(compressedFile)
                reader.onload = function (res) {
                    _this.ajax(_this.option.upload_url, {
                        blob: res.target.result,
                        name: imageFile.name,
                        type: 'image'
                    }, (res) => {
                        if (res.data.path) {
                            _this.comment.files.push(res.data.path);
                            storage.set('comment_files', _this.comment.files);
                            _this.renderFiles();

                        }
                    })
                }
            }
        } catch (error) {
            console.log('上传图片出错:' + JSON.stringify(error));
        }

    },
    page: 1,
    load_all: false,
    sort: '',
    reload() {
        this.page = 1;
        $('.qcmt-list').html('');
        this.load();
    },
    load() {
        let _this = this;
        $('.qcmt-load-more').remove();
        this.ajax(this.option.load_url, {
            data_id: this.option.data_id,
            type: this.option.type,
            page: this.page,
            sort: this.sort,
        }, (res) => {
            if (res.data) {
                let html = doT.template(item_tpl)(res.data);
                $('.qcmt-list').append(html);
                if (res.data && res.data.length < 10) {
                    _this.load_all = true;

                    if($('.qcmt-list .qcmt-item').length==0){
                        $('.qcmt-list').append('<div class="qcmt-no-comment"> - 暂无评论 - </div>');
                    }else{
                        $('.qcmt-list').append('<div class="qcmt-load-all"> - 加载完毕 - </div>');
                    }

                } else {
                    $('.qcmt-list').append('<div class="qcmt-load-more">点击加载更多</div>');
                }

                _this.require('lazyload', () => {
                    if (!window.lazy) {
                        window.lazy = new lazyload();
                    } else {
                        lazy.updateImages();
                    }
                })
            }
            _this.page++;
        })

    },


    ajax: function (url, data, callback, processData, dataType) {
        let _this = this, 
            handle = typeof processData != "undefined" ? processData : true,
            type = typeof data != "object" ? "get" : "post";

        var api_server = this.option['api_server'] || this.url(), _url;

        if (url.indexOf("http") < 0) {
            _url = api_server + url;
        } else {
            _url = url;
        }
        
        // 删除签名字段
        delete data['_'];
        
        // 添加current_user_id到请求数据
        if(this.option.current_user_id) {
            data['current_user_id'] = this.option.current_user_id;
        }
        
        // 生成签名
        var tmp = Object.keys(data).sort();
        data['_'] = md5(JSON.stringify(tmp));

        dataType = dataType ? dataType : 'json';
        _url = _url.replace(/\/{3,}/gi, "/");
        callback = (typeof callback == "undefined" && typeof data == "function") ? data : callback;

        // 构建headers
        let headers = {
            'X-Requested-With': 'XMLHttpRequest',
            'X-Current-User-Id': this.option.current_user_id || ''
        };

        // 合并自定义headers
        if(this.option.headers && typeof this.option.headers === 'object') {
            headers = {...headers, ...this.option.headers};
        }

        var option = {
            url: _url,
            xhrFields: {
                withCredentials: true
            },
            headers: headers, // 添加headers
            data: data,
            dataType: dataType,
            type: type,
            processData: handle,
            success: function (response, status, xhr) {
                if (response && typeof response.msg != "undefined" && response.msg) {
                    let type = response.code !== 200 ? "error" : "success";
                    _this.msg(response.msg, type);
                }
                if (_this.isCallback(callback)) {
                    callback(response);
                }
            },
            fail: function (res) {
                console.info('ajax error', JSON.stringify(res));
                _this.msg('请求失败:' + res.statusText, 'error');
            },
            error(res) {
                console.info('ajax error', JSON.stringify(res));
                _this.msg('请求失败,请确认服务器地址是否正确', 'error');
            }
        };

        if (typeof processData === false) {
            option.contentType = false;
        }

        $.ajax(option);
    },
    require(js, callback) {

        var jses = typeof js == "string" ? [js] : js, _this = this;

        for (var i in jses) {

            var _js = jses[i],
                _js_ = typeof this.STATIC[_js] != "undefined" ?
                    this.STATIC[_js] : '';

            if (_js_ && _js_.indexOf('./') > -1) {
                _js_ = this.url() + '/static/js/' + (_js_.replace('./', ''));
            }


            if (_js_ && typeof window[_js] == "undefined") {

                _js_ && this.loadScript(_js_, function (params) {

                    if (typeof window[_js] == "undefined") {
                        window[_js] = 1;
                    }

                    if (params.index == params.length - 1) {
                        // console.log(jses, jses.length, params.js, '回调')
                        if (_this.isCallback(callback)) {
                            callback();
                        }
                    }
                }, {index: i, length: jses.length, js: _js_});

            } else {
                // console.log(i, jses.length - 1, i === jses.length - 1, _js_)
                if (Number(i) === jses.length - 1) {
                    if (_this.isCallback(callback)) {
                        callback();
                    }
                }
            }
        }
    },

    removeItem: function (arr, val) {
        return arr.filter(function (i) {
            return i !== val;
        })
    },
    formatAgo(str) {
        if (!str) return '';
        const date_time = str.toString().indexOf('-') > -1 ? new Date(str).getTime() : str * 1000;
        const time = new Date().getTime() - date_time; // 现在的时间-传入的时间 = 相差的时间（单位 = 毫秒）
        if (time < 0) {
            return '';
        } else if (time / 1000 < 30) {
            return '刚刚';
        } else if (time / 1000 < 60) {
            return parseInt(String(time / 1000)) + '秒前';
        } else if (time / 60000 < 60) {
            return parseInt(String(time / 60000)) + '分钟前';
        } else if (time / 3600000 < 24) {
            return parseInt(String(time / 3600000)) + '小时前';
        } else if (time / 86400000 < 31) {
            return parseInt(String(time / 86400000)) + '天前';
        } else if (time / 2592000000 < 12) {
            return parseInt(String(time / 2592000000)) + '月前';
        } else {
            return parseInt(String(time / 31536000000)) + '年前';
        }
    },
    msg(msg, type = 'success', callback) {
        // 移除已存在的toast
        const existingToast = document.querySelector('.qcmt_toast');
        if (existingToast) {
            existingToast.remove();
        }

        // 创建新的toast
        const toast = document.createElement('div');
        toast.className = 'qcmt_toast';
        
        // 添加图标
        if (type !== 'none') {
            const icon = document.createElement('div');
            icon.className = `qcmt_toast_icon ${type}`;
            toast.appendChild(icon);
        }
        
        // 添加文本内容
        const content = document.createElement('div');
        content.className = 'qcmt_toast_content';
        content.textContent = msg;
        toast.appendChild(content);
        
        // 添加到页面
        document.body.appendChild(toast);
        
        // 触发动画
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);
        
        // 自动关闭
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                toast.remove();
                if (typeof callback === 'function') {
                    callback();
                }
            }, 300);
        }, 2000);
    },
    cloneObj: function (obj) {
        let str,
            newobj = obj.constructor === Array ? [] : {};
        if (typeof obj !== "object") {
            return;
        } else if (window.JSON) {
            (str = JSON.stringify(obj)), //系列化对象
                (newobj = JSON.parse(str)); //还原
        } else {
            for (let i in obj) {
                newobj[i] =
                    typeof obj[i] === "object" ? cloneObj(obj[i]) : obj[i];
            }
        }
        return newobj;
    },
    async loadScript(url, callback, params) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        if (typeof (callback) != "undefined") {
            if (script.readyState) {
                script.onreadystatechange = function () {
                    if (script.readyState == "loaded" || script.readyState == "complete") {
                        script.onreadystatechange = null;
                        callback(params);
                    }
                };
            } else {
                script.onload = function () {
                    callback(params);
                };
            }
        }
        script.src = url;
        document.head.appendChild(script);
    },
    isCallback: function (callback) {
        return typeof callback == "function";
    },

    /**
     *
     * @param url
     * @returns {{path: string, protocol: string, file: string | string, port: string, query: string, host: string, source, params: {}, hash: string, relative: string | string, segments: string[]}}
     */
    parseURL(url) {
        let a = document.createElement("a");
        a.href = url;
        return {
            source: url,
            protocol: a.protocol.replace(":", ""),
            host: a.hostname,
            port: a.port,
            query: a.search,
            params: (function () {
                let ret = {},
                    seg = a.search.replace(/^\?/, "").split("&"),
                    len = seg.length,
                    i = 0,
                    s;
                for (; i < len; i++) {
                    if (!seg[i]) {
                        continue;
                    }
                    s = seg[i].split("=");
                    ret[s[0]] = s[1];
                }
                return ret;
            })(),
            file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ""])[1],
            hash: a.hash.replace("#", ""),
            path: a.pathname.replace(/^([^\/])/, "/$1"),
            relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ""])[1],
            segments: a.pathname.replace(/^\//, "").split("/"),
        };
    },

    showAnonymousForm() {
        // 创建匿名信息输入表单
        const form = `
            <div class="anonymous-form">
                <input type="text" class="nickname" placeholder="请输入昵称(必填)" />
                <div class="avatar-list">
                    ${this.config.anonymous_avatars.map(avatar => 
                        `<img src="${avatar}" class="avatar-option" />`
                    ).join('')}
                </div>
            </div>
        `;
        
        // 添加到评论框前
        this.commentBox.insertAdjacentHTML('beforebegin', form);
        
        // 绑定头像选择事件
        this.bindAvatarSelection();
    },

    submitComment() {
        if(!this.user_id) {
            const nickname = this.el.querySelector('.qcmt-anonymous-nickname').value;
            const email = this.el.querySelector('.qcmt-anonymous-email').value;
            const selectedAvatar = this.el.querySelector('.qcmt-avatar-option.selected');
            
            if(!nickname || !selectedAvatar) {
                this.msg('请填写昵称并选择头像', 'error');
                return;
            }
            
            // 验证邮箱格式(如果填写了的话)
            if(email && !this.validateEmail(email)) {
                this.msg('请输入正确的邮箱格式', 'error');
                return;
            }
            
            this.params.anonymous = {
                nickname: nickname,
                avatar: selectedAvatar.src,
                email: email
            };
        }
        
        // 继续原有的提交逻辑
    },

    renderCommentBox() {
        let html = `<div class="qcmt-input-box">`;
        
        if(this.option.allow_anonymous && !this.user_id) {
            html += `
                <div class="qcmt-anonymous-form">
                    <div class="qcmt-input-group">
                        <input type="text" class="qcmt-anonymous-nickname" placeholder="请输入昵称(必填)" maxlength="20">
                        <input type="email" class="qcmt-anonymous-email" placeholder="邮箱(选填,有回复时通知)" maxlength="100">
                    </div>
                    <div class="qcmt-avatar-list">
                        ${this.option.anonymous_avatars.map(avatar => 
                            `<img src="${this.cdn(avatar)}" class="qcmt-avatar-option" alt="选择头像">`
                        ).join('')}
                    </div>
                </div>
            `;
        }

        html += `
            <textarea id="qcmt-content" placeholder="说点什么..."></textarea>
            <div class="qcmt-toolbar">
                <span class="qcmt-face"><i class="iconfont icon-face"></i></span>
                <span class="qcmt-image"><i class="iconfont icon-image"></i></span>
                <input type="file" id="qcmt-image" accept="image/*" style="display: none">
                <span class="qcmt-record" id="qcmt-record"><i class="iconfont icon-record"></i></span>
                <button class="qcmt-btn">发布</button>
            </div>
        </div>`;

        return html;
    },

    generateUserId() {
        const ua = navigator.userAgent;
        const timestamp = new Date().getTime();
        return 'anonymous_' + md5(ua + timestamp).substr(0, 16);
    },

    // 添加清除匿名信息的方法(可选)
    clearAnonymousInfo() {
        localStorage.removeItem('qcmt_anonymous_id');
        localStorage.removeItem('qcmt_anonymous_nickname');
        localStorage.removeItem('qcmt_anonymous_avatar');
    },

    submitCheck() {
        const lastSubmitTime = localStorage.getItem('qcmt_last_submit_time');
        const now = new Date().getTime();
        
        if(lastSubmitTime && (now - parseInt(lastSubmitTime)) < this.option.submit_interval * 1000) {
            this.msg(`请等待 ${this.option.submit_interval} 秒后再发布`, 'error');
            return false;
        }
        
        if(!this.comment.content.trim() && !this.comment.files.length) {
            this.msg('评论内容不能为空', 'error');
            return false;
        }
        
        if(this.comment.content.length < this.option.content_min_length) {
            this.msg(`评论内容至少 ${this.option.content_min_length} 个字符`, 'error');
            return false;
        }
        
        if(this.comment.content.length > this.option.content_max_length) {
            this.msg(`评论内容不能超过 ${this.option.content_max_length} 个字符`, 'error');
            return false;
        }
        
        return true;
    },

    // 添加邮箱验证方法
    validateEmail(email) {
        const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
    },
}

